package com.seqb.manage.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.exception.BdException;
import com.seqb.manage.role.dao.RoleDao;
import com.seqb.manage.role.dao.RoleMenuDao;
import com.seqb.manage.role.domain.RoleDO;
import com.seqb.manage.role.domain.RoleMenuDO;
import com.seqb.manage.role.service.RoleMenuService;
import com.seqb.manage.role.service.RoleService;
import com.seqb.manage.user.dao.UserRoleDao;
import com.seqb.manage.user.domain.UserRoleDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/14
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleMenuDao roleMenuDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public RoleDO get(Long id) {
        return roleDao.selectById(id);
    }

    @Override
    public Page<RoleDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, RoleDO.class);
        return (Page<RoleDO>) roleDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, RoleDO.class);
        return roleDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(RoleDO role) {
        try {
            String name = role.getName();
            if (StringUtils.isEmpty(name)) {
                return ResultVo.error("参数不足！");
            }
            int insert = roleDao.insert(role);
            if (insert <= 0) {
                throw new BdException("操作失败！");
            }
            //先删除原来的角色菜单权限
            Long roleId = role.getId();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id", roleId);
            roleMenuDao.delete(queryWrapper);
            //再新增选择的权限
            String ids = role.getIds();
            if (StringUtils.isNotEmpty(ids)) {
                String[] menuIds = ids.split(",");
                List<RoleMenuDO> roleMenuList = new ArrayList<>();
                for (String menuId : menuIds) {
                    RoleMenuDO roleMenuDO = new RoleMenuDO();
                    roleMenuDO.setRoleId(roleId);
                    roleMenuDO.setMenuId(Long.valueOf(menuId));
                    roleMenuList.add(roleMenuDO);
                }
                if (roleMenuList.size() > 0) {
                    boolean batch = roleMenuService.saveBatch(roleMenuList);
                    if (!batch) {
                        throw new BdException("操作失败！");
                    }
                }
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo update(RoleDO role) {
        try {
            Long roleId = role.getId();
            String name = role.getName();
            if (null == roleId || StringUtils.isEmpty(name)) {
                return ResultVo.error("参数不足！");
            }
            int insert = roleDao.updateById(role);
            if (insert <= 0) {
                throw new BdException("操作失败！");
            }
            //先删除原来的角色菜单权限
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("role_id", roleId);
            roleMenuDao.delete(queryWrapper);
            //再新增选择的权限
            String ids = role.getIds();
            if (StringUtils.isNotEmpty(ids)) {
                String[] menuIds = ids.split(",");
                List<RoleMenuDO> roleMenuList = new ArrayList<>();
                for (String menuId : menuIds) {
                    RoleMenuDO roleMenuDO = new RoleMenuDO();
                    roleMenuDO.setRoleId(roleId);
                    roleMenuDO.setMenuId(Long.valueOf(menuId));
                    roleMenuList.add(roleMenuDO);
                }
                if (roleMenuList.size() > 0) {
                    boolean batch = roleMenuService.saveBatch(roleMenuList);
                    if (!batch) {
                        throw new BdException("操作失败！");
                    }
                }
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Long id) {
        return roleDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemove(Long[] ids) {
        return roleDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<RoleDO> listUserRole(Long userId) {
        List<RoleDO> roleList = roleDao.selectList(null);
        try {
            if (null != userId) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("user_id", userId);
                List<UserRoleDO> userRolelist = userRoleDao.selectList(queryWrapper);
                List selectRoleIds = new ArrayList();
                if (null != userRolelist && userRolelist.size() > 0) {
                    for (UserRoleDO userRole : userRolelist) {
                        selectRoleIds.add(userRole.getRoleId());
                    }
                }
                if (null != roleList && roleList.size() > 0) {
                    for (RoleDO role : roleList) {
                        if (selectRoleIds.contains(role.getId())) {
                            role.setSign("true");
                        } else {
                            role.setSign("false");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roleList;
    }

}
